/*
 * Script containing the AddEdgeController
 * 
 * Author: Chris Casola
 */

/**
 * Responds to click events on the edge canvas
 */
function AddEdgeController(event) {
	
	var clickPos = getClickPosition(event, document.getElementById('edgeCanvas'));
	var leftChoice = edgeInfo(clickPos.x);
	
	if (window.dlEvent.currentPlayer != window.dlEvent.playerPosition) {
		alert('it is not your turn');
		return;
	}
	
	if (window.dlEvent.addEdge(leftChoice, clickPos.y)) {
		// TODO send the edge to the server and draw the edge in the response handler
		sendRequest(new addEdgeRequest(leftChoice, leftChoice + 1, clickPos.y));	
	}
	else {
		alert("Invalid edge!");
	}
}

/**
 * Returns the choice directly to the left of the given x position
 */
function edgeInfo(xPos) {
	var i;
	for (i=0; i < (window.choicePositions.length - 1); i++) {
		if ((xPos > window.choicePositions[i]) && (xPos < window.choicePositions[i+1])) {
			return i;
		}
	}
}

/**
 * This functions gets the position of the mouse click on the canvas
 */
function getClickPosition(event, canvas) {
	return canvas.relMouseCoords(event);
}

/**
 * Helper function to compute the mouse click position relative
 * to the canvas.
 * 
 * THIS CODE COURTESY OF: Ryan Artecona
 * FROM: http://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element
 */
function relMouseCoords(event){
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var canvasX = 0;
    var canvasY = 0;
    var currentElement = this;

    do{
        totalOffsetX += currentElement.offsetLeft;
        totalOffsetY += currentElement.offsetTop;
    }
    while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;